<?php
// +----------------------------------------------------------------------
// | Citrix [ WE ONLY DO WHAT IS NECESSARY ]
// +----------------------------------------------------------------------
// | Copyright (c) 2018 http://www.tpCitrix.com/ All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.tpCitrix.com/ )
// +----------------------------------------------------------------------
// | Author: Citrix < 2722279500@qq.com >
// +----------------------------------------------------------------------
namespace app\admin\controller;
use \think\Cache;
use \think\Controller;
use think\Loader;
use think\Db;
use \think\Cookie;
use \think\Session;
use app\admin\model\Users as usersModel;
use app\admin\controller\Permissions;
class Users extends Permissions
{
    public function index()
    {
        $model = new usersModel();
        $post = $this->request->param();
        if (isset($post['keywords']) and !empty($post['keywords'])) {
            $where['fullname'] = ['like', '%' . $post['keywords'] . '%'];
        }
       
        if (isset($post['admin_id']) and $post['admin_id'] > 0) {
            $where['admin_id'] = $post['admin_id'];
        }
        
        if (isset($post['status']) and ($post['status'] == 1 or $post['status'] === '0')) {
            $where['status'] = $post['status'];
        }

        if(isset($post['create_time']) and !empty($post['create_time'])) {
            $min_time = strtotime($post['create_time']);
            $max_time = $min_time + 24 * 60 * 60;
            $where['create_time'] = [['>=',$min_time],['<=',$max_time]];
        }
        
        $users = empty($where) ? $model->order('create_time desc')->paginate(20) : $model->where($where)->order('create_time desc')->paginate(20,false,['query'=>$this->request->param()]);

        //$users = $article->toArray();
        //添加最后修改人的name
        foreach ($users as $key => $value) {
            $users[$key]['edit_admin'] = Db::name('admin')->where('id',$value['edit_admin_id'])->value('nickname');
        }
        $this->assign('users',$users);
        $info['cate'] = Db::name('article_cate')->select();
        $info['admin'] = Db::name('admin')->select();
        $this->assign('info',$info);
        return $this->fetch();
    }


    public function publish()
    {
    	//获取菜单id
    	$id = $this->request->has('id') ? $this->request->param('id', 0, 'intval') : 0;
    	$model = new usersModel();

		//是正常添加操作
		if($id > 0) {
    		//是修改操作
    		if($this->request->isPost()) {
    			//是提交操作
    			$post = $this->request->post();
    			//验证  唯一规则： 表名，字段名，排除主键值，主键名
	            $validate = new \think\Validate([
                    ['user', 'require', '账号不能为空'],
                    ['fullname', 'require', '姓名不能为空'],
                    ['company', 'require', '公司全称不能为空'],
                    ['m_title', 'require', '所在部门不能为空'],
                    ['email', 'require', '邮箱不能为空'],
                    ['mobile', 'require', '手机不能为空'],
                ]);
                if(!preg_match("/^1[34578]\d{9}$/", $post['mobile']))
                {
                    $this->error('提交失败：手机格式不正确');
                }
                if(!preg_match("/^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,})$/",$post['email']))
                {
                    $this->error('提交失败：邮箱格式不正确');
                }
                if(!preg_match("/^[a-z\d]*$/i",$post['user']))
                {
                    $this->error('账号只能包含数字和字母');
                }
                if(!empty($post['newpass']) || !empty($post['newpass_confirm']))
                {
                    if(password($post['newpass']) != password($post['newpass_confirm']))
                    {
                        $this->error('提交失败：二次输入密码不正确');
                    }
                }
                if(true == Db::name('users')->where('user',$post['user'])->where('id','neq',$id)->count())
                {
                    $this->error('账号已存在');
                }
                if(!empty($post['newpass']) && !empty($post['newpass_confirm']))
                {
                    $post['newpass'] = password($post['newpass']);
                }else
                {
                    unset($post['newpass']);
                }
	            //验证部分数据合法性
	            if (!$validate->check($post)) {
	                $this->error('提交失败：' . $validate->getError());
	            }
	            //验证菜单是否存在
	            $users = $model->where('id',$id)->find();
	            if(empty($users)) {
	            	return $this->error('id不正确');
	            }
                //设置修改人
                $post['edit_admin_id'] = Session::get('admin');
	            if(false == $model->allowField(true)->save($post,['id'=>$id])) {
	            	return $this->error('修改失败');
	            } else {
                    addlog($model->id);//写入日志
	            	return $this->success('修改成功','admin/users/index');
	            }
    		} else {
    			//非提交操作
    			$users = $model->where('id',$id)->find();
    			if(!empty($users)) {
    				$this->assign('users',$users);
    				return $this->fetch();
    			} else {
    				return $this->error('id不正确');
    			}
    		}
    	} else {
    		//是新增操作
    		if($this->request->isPost()) {
    			//是提交操作
    			$post = $this->request->post();
    			//验证  唯一规则： 表名，字段名，排除主键值，主键名
	            $validate = new \think\Validate([
	                ['user', 'require', '账号不能为空'],
                    ['newpass', 'require', '密码不能为空'],
                    ['newpass_confirm', 'require', '确认密码不能为空'],
                    ['fullname', 'require', '姓名不能为空'],
                    ['company', 'require', '公司全称不能为空'],
                    ['m_title', 'require', '所在部门不能为空'],
                    ['email', 'require', '邮箱不能为空'],
                    ['mobile', 'require', '手机不能为空'],
	            ]);
                if(!preg_match("/^1[34578]\d{9}$/", $post['mobile']))
                {
                    $this->error('提交失败：手机格式不正确');
                }
                if(!preg_match("/^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,})$/",$post['email']))
                {
                    $this->error('提交失败：邮箱格式不正确');
                }
                if(password($post['newpass']) != password($post['newpass_confirm']))
                {
                    $this->error('提交失败：二次输入密码不正确');
                }
                if(!preg_match("/^[a-z\d]*$/i",$post['user']))
                {
                    $this->error('账号只能包含数字和字母');
                }
                if(true == Db::name('users')->where('user',$post['user'])->count())
                {
                    $this->error('账号已存在');
                }
                $post['newpass'] = password($post['newpass']);
	            //验证部分数据合法性
	            if (!$validate->check($post)) {
	                $this->error('提交失败：' . $validate->getError());
	            }
                //设置创建人
                $post['admin_id'] = Session::get('admin');
                //设置修改人
                $post['edit_admin_id'] = $post['admin_id'];
	            if(false == $model->allowField(true)->save($post)) {
	            	return $this->error('添加失败');
	            } else {
                    addlog($model->id);//写入日志
	            	return $this->success('添加成功','admin/users/index');
	            }
    		} else {
    			//非提交操作
    			return $this->fetch();
    		}
    	}
    	
    }

    public function status()
    {
        if($this->request->isPost()){
            $post = $this->request->post();
            if(false == Db::name('users')->where('id',$post['id'])->update(['status'=>$post['status']])) {
                return $this->error('设置失败');
            } else {
                addlog($post['id']);//写入日志
                return $this->success('设置成功','admin/users/index');
            }
        }
    }

}
